import React, {Component} from 'react'
import {View, Text, TouchableOpacity, TextInput, Alert, ScrollView, FlatList} from 'react-native'
import styles, {BLUE, RED, borderBottomLine, LARGE} from '../../config/styles'
import Loading from '../common/loading_common'
import HeadingLine from '../common/heading_line'
import {GetTaskApi, PostStudentTaskAnswerApi, PutRetractTaskApi} from '../../config/api'
import AttachmentManagerPro from '../common/attachmentManagerPro'

class StudentHomeworkShow extends Component {

    static navigationOptions = ({ navigation }) => {
        const params = navigation.state.params
        if (params != undefined && params.status != undefined) {
            const _headerRight = params.status == 'finished' ? <View /> : (<TouchableOpacity
                                        style={{paddingRight: 5}}
                                        onPress={params.submit}
                                    >
                                        <Text style={[styles.header_font]}>
                                            {['init', 'revising'].includes(params.status) ? '提交' : '撤回'}
                                        </Text>   
                                    </TouchableOpacity>
                                )
            return {
                headerRight: _headerRight
            }
        } 
    } 


    constructor (props) {
        super(props);
        const {params} = props.navigation.state
        this.state = {
            id: params.id,
            homework_id: params.homework_id,
            data: {},
            current_audio: {},
            task_answers: [],
            current_task_answer: {},
            task_student: {},
            afterSubmit: params.afterSubmit,
            loading: true,
            objectForSubmit: {
                attachments: [],
                content: "",
                task_id: params.id
            }
        }
    }
    

    componentDidMount() {
        let {objectForSubmit, current_audio, task_student, id, homework_id} = this.state
        GetTaskApi(id, homework_id).then((data) => {
            const {task_student, current_task_answer} = data
            let _current_audio
            if (['init', 'revising'].includes(task_student.status)) {
                _current_audio = {}
            } else {
                _current_audio = current_task_answer.attachments.filter((a) => {
                    return a.sub_type == 1
                })[0]
                current_task_answer.attachments = current_task_answer.attachments.filter((a) => {
                    return a.sub_type != 1
                })
            }
            
            this.setState({
                loading: false,
                data: data.task,
                task_answers: data.task_answers,
                current_task_answer: current_task_answer || {},
                task_student: task_student,
                current_audio: _current_audio
            })

            this.setTitleBtn()
        })

    }

    setTitleBtn = () => {
        let {objectForSubmit, current_audio, task_student, id, homework_id, current_task_answer, afterSubmit} = this.state
        this.props.navigation.setParams({
            status: task_student.status,
            submit: () => {
                if (['revised', 'answered'].includes(task_student.status)) {
                    PutRetractTaskApi(current_task_answer.id).then((data) => {
                        if (data.code == 0) {
                            afterSubmit()
                            task_student.status = 'init'
                            Toast.show('撤回成功')
                            this.props.navigation.goBack()
                            //this.setState({}, () => this.setTitleBtn())
                        } else {
                            Toast.show('撤回失败')
                            return
                        }
                    })

                } else if (['revising', 'init'].includes(task_student.status)) {
                    if (Object.keys(current_audio).length == 0) {
                        Toast.show('请录音后提交')
                        return
                    }
                    objectForSubmit.attachments.push(current_audio)
                    PostStudentTaskAnswerApi(objectForSubmit).then((data) => {
                        if (data.code == 0) {
                            afterSubmit()
                            Toast.show('提交成功')
                            this.props.navigation.goBack()
                        } else {
                            Toast.show('提交失败')
                            return
                        }
                    })
                }
            }
        })
    }

    //附件完成上传之后
    onFinishedUpload = (name, type, awsPath) => {
        let _onDestroy = () => {this.onRemoveAttachment(name)}
        let new_attachment = {
            type: type,
            url: awsPath,
            name: name,
            allowDestroy: true,
            onDestroy: _onDestroy
        }
        let _objectForSubmit = this.state.objectForSubmit
        _objectForSubmit.attachments.push(new_attachment)
        this.setState({})
    }

    //点击角标删除attachment的事件
    onRemoveAttachment = (attachment_name) => {
        Alert.alert('删除提醒', '确认要删除这个附件吗？',[
                {text: '取消', onPress: () => {}},
                {text: '确定', onPress: () => {
                    let _attachments = this.state.objectForSubmit.attachments.filter((atta, index) => {
                        return atta.name != attachment_name
                    })
                    let _objectForSubmit = this.state.objectForSubmit
                    _objectForSubmit.attachments = _attachments
                    this.setState({})
                }}
            ]
        )
    }

    isNewTask = () => {
        const {task_student, current_audio} = this.state
        return (['init', 'revising'].includes(task_student.status) && Object.keys(current_audio).length == 0)
    }

     //设置课文
    setContent = (txt) => {
        let _objectForSubmit = this.state.objectForSubmit
        _objectForSubmit.content = txt
        this.setState({objectForSubmit: _objectForSubmit})
    }

    //去录音
    goToRecord = (task) => {
        const {navigation} = this.props
        const {data, id, current_audio, task_student} = this.state
        navigation.navigate('student_do_homework', {
            task_id: id, 
            title: data.section,
            content: data.section_content,
            current_audio_path: current_audio.url,
            rerecordAllow: !['finished', 'revised'].includes(task_student.status),
            contentDisplay: !data.need_recite,
            afterRecord: (audio) => {
                this.setState({current_audio: audio})
                this.setTitleBtn()
                //current_audio = audio
            }
        })
    }

    RecordBtnText = () => {
        if (this.isNewTask()) {
            return "准备好了，去录音  >"
        } else {
            return "听录音"
        }
    }

    _keyExtractor = (item, index) => index


    render () {
        const {loading, data, objectForSubmit, id, current_task_answer, task_student, task_answers} = this.state
        const {task_reply} = current_task_answer
        const {navigation} = this.props
        if (loading) {
            return <Loading />
        } else {
            return (
                <ScrollView style={{flex: 1}}>
                    <View style={{backgroundColor: 'white', padding: 10}}>
                        <View style={{flexDirection: 'row'}}>
                                <Text style={{flex: 1}}>教材: {data.textbook}</Text>
                                {data.need_recite ? (
                                    <View style={[styles.tag_container, {borderColor: BLUE}]}>
                                        <Text>背诵</Text>
                                    </View>
                                ) : null}
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                                <Text style={{flex: 1}}>单元: {data.chapter}</Text>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                                <Text style={{flex: 1}}>课文: {data.section}</Text>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                                <Text style={{flex: 1}}>提醒: {data.content}</Text>
                        </View>
                        <TouchableOpacity 
                                style={[styles.as_large_button, styles.background_blue, {marginTop: 10}]}
                                onPress={this.goToRecord}
                            >
                                <Text style={styles.text_white}>{this.RecordBtnText()}</Text>
                        </TouchableOpacity>

                        {['revising', 'init'].includes(task_student.status) ? (
                            <View style={{ height: 150, padding: 10}}>
                                <TextInput 
                                    style={[styles.background_light_grey_plus, {padding: 0, flex: 1}]}
                                    placeholder={'输入您想说的话'}
                                    onChangeText={this.setContent} 
                                    value={objectForSubmit.content}
                                    multiline={true}
                                    textAlignVertical={'top'}/></View>) : 
                            (<View style={{paddingTop: 10}}>
                                <Text>学生留言:</Text>
                                <Text>{current_task_answer.content}</Text>
                            </View>)
                        }

                      

                        {this.isNewTask() ? (
                            <AttachmentManagerPro onFinishedUpload={this.onFinishedUpload} attachments={objectForSubmit.attachments} />
 
                        ) : (
                            <AttachmentManagerPro attachments={current_task_answer.attachments} />
                        )}

                      
                    </View>

                      {/*教师是否批改*/}
                    {['finished', 'revising', 'revised'].includes(task_student.status) && task_reply != undefined ? (
                        <View style={{backgroundColor: 'white', marginTop: 10}}>
                            <HeadingLine title={'教师点评'} color={RED} collapsible={false}>
                                <AttachmentManagerPro attachments={task_reply.attachments} />

                                <View style={{height: 0.3, backgroundColor: borderBottomLine, margin: 5}} />

                                <View style={{margin: 10}}>
                                    <Text>教师留言</Text>
                                    <Text style={{padding: 10}}>{task_reply.content}</Text>
                                </View>

                                <View style={{height: 0.3, backgroundColor: borderBottomLine, margin: 5}} />

                                <View style={{alignItems: 'center', margin: 10}}>
                                    <Text>
                                        本次作业得分 
                                        <Text style={{color: RED, fontSize: LARGE}}>{task_reply.score} {task_student.status == 'revising' ? '需订正' : ''}</Text>
                                    </Text>
                                </View>

                            </HeadingLine>
                        </View>
                           
                        ) : null
                    }

                    {task_answers.length > 0 ? (
                         <View style={{height: 0.3, backgroundColor: borderBottomLine, margin: 5}} >
                            <View style={{alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(0,0,0,0)'}}>
                                <Text>历史作业</Text>
                            </View>   
                        </View>
                    ) : null}
                   

                    <FlatList 
                        data={task_answers} 
                        keyExtractor={this._keyExtractor}
                        renderItem={({item}) => {return(
                            <View style={{margin: 10, backgroundColor: 'white', padding: 10, flex: 1}}>
                                <View><Text style={{color: BLUE}}>{item.created_at}</Text></View>
                                <View style={{paddingTop: 5}}><Text numberOfLines={1}>留言: {item.task_reply.content}</Text></View>
                                <View style={{paddingTop: 5}}><Text>附件数: {item.attachments.length}</Text></View>
                            </View>
                        )}}
                        horizontal={true}
                    />


                </ScrollView>
            )
        }
       
    }
}

export default StudentHomeworkShow